package com.test.asmtest;

import java.util.Stack;

/**
 * created by lpw
 */
public class TestClass {
    public static void main(String[] args) {
        Node node = createLinked();
        boolean b = hasCircle(node);
        System.out.println(b);
    }

    /**
     *检测环
     */
    public static boolean hasCircle(Node head){
        if (head ==null ){
            return false;
        }
        Node quick=head.next;
        Node slow=head;
        /**
         * 快慢指针一块走，如果有环，这个循环永远也出不来，一定会存在slow==quick
         * 如果没环，则会走到最后一个节点，跳出循环
         */
        while (quick!=null && quick.next!=null){
            slow=slow.next;
            quick=quick.next.next;
            if (slow==quick){
                return true;
            }
        }
        return false;
    }

    //打印链表
    public static void logNode(Node node){
        Node temp=node;
        while (temp!=null){
            System.out.println(temp.data);
            temp=temp.next;
        }
    }

    //生成链表,建了一个换
    public static Node createLinked(){
        Node node1=new Node("A");
        Node node2=new Node("B");
        Node node3=new Node("C");
        Node node4=new Node("D");
        Node node5=new Node("E");
        Node node6=new Node("F");
        Node node7=new Node("G");
        Node node8=new Node("H");
        Node node9=new Node("I");

        node1.next=node2;
        node2.next=node3;
        node3.next=node4;
        node4.next=node5;
        node5.next=node6;
        node6.next=node7;
        node7.next=node8;
        node8.next=node9;
        node9.next=node3;
        return node1;
    }

    //使用遍历反转链表
    public static Node linkedReversal(Node oldNode){
        if (oldNode == null) return null;
        Node pre = oldNode;
        Node cur = oldNode.next;
        Node temp;
        while (cur != null) {// 为空，说明到最后了
            temp = cur.next;
            cur.next=pre;// 反转指针域的指向
            // 指针往下移动
            pre = cur;
            cur = temp;
        }
        // 最后将原链表的头节点的指针域置为null，还回新链表的头结点，即原链表的尾结点
        oldNode.next=null;
        return pre;
    }
}

class Node {
    String data;
    Node next;

    public Node(String data) {
        this.data = data;
    }
}